import 'dart:async';
import 'dart:developer';
import 'package:flutter/services.dart';
import 'package:lighthouse/index.dart';
import 'forget_password_next.dart';

class ForgetPasswordPage extends StatefulWidget {
  const ForgetPasswordPage({Key? key}) : super(key: key);

  @override
  State createState() => _ForgetPasswordState();
}

class Params {
  final String phone;
  final String username;

  Params(this.phone, this.username);
}

//  手机号码
const phoneRes = r"(13\d|14[579]|15[^4\D]|17[^49\D]|18\d)\d{8}";

class _ForgetPasswordState extends State<ForgetPasswordPage> {
  //表单状态
  final _formKey = GlobalKey<FormState>();

  //输入框控制器
  final TextEditingController _phoneController = TextEditingController();
  final TextEditingController _codeController = TextEditingController();

  //焦点
  final FocusNode _focusPhone = FocusNode();
  final FocusNode _focusCode = FocusNode();

  int _countdownTime = 0;
  Timer? _timer;
  String _realName = '';

  @override
  Widget build(BuildContext context) {
    var darkModel = Provider.of<DarkModel>(context);
    return GlobalStyle(
      child: BackgroundStyleWidget(
        child: Scaffold(
            backgroundColor: Colors.transparent,
            appBar: AppBar(
              backgroundColor: Colors.transparent,
              systemOverlayStyle: darkModel.isDark(context)
                  ? SystemUiOverlayStyle.light
                  : SystemUiOverlayStyle.dark,
              title: const Text('忘记密码'),
              centerTitle: true,
            ),
            body: _bodyView()),
      ),
    );
  }

  @override
  void deactivate() {
    ///清楚倒计时
    // _timer?.cancel();
    super.deactivate();
  }

  Widget _bodyView() {
    return Padding(
        padding: const EdgeInsets.all(16),
        child: Column(
          children: [
            Container(
              width: double.infinity,
              padding: const EdgeInsets.only(top: 30, bottom: 30),
              child: Text('请重新编辑您的密码',
                  style: Theme.of(context).textTheme.titleMedium?.copyWith(
                      color: Theme.of(context).colorScheme.onPrimary)),
            ),
            _inputView(
                'me_username', _phoneController, false, '请输入手机号', (value) {}),
            const SizedBox(height: 20),
            Stack(
              children: [
                _inputView(
                    'me_code', _codeController, false, '请输入短信验证码', (value) {}),
                Positioned(
                  top: 0,
                  right: 10,
                  child: _codeTimeOut(),
                )
              ],
            ),
            const SizedBox(height: 30),
            SizedBox(
              width: double.infinity,
              child: CommonButton.elevatedButton(context, text: "下一步",
                  onPressed: () {
                if (!_phoneController.text.isNotEmpty ||
                    !_codeController.text.isNotEmpty) {
                  showToast("请填写手机号、验证码");
                  return;
                }
                _nextStep();
              }),
            )
          ],
        ));
  }

  ///倒计时
  void startCountdownTimer() {
    const oneSec = Duration(seconds: 1);
    callback(timer) {
      setState(() {
        if (_countdownTime < 1) {
          _timer?.cancel();
          _codeTimeOut();
        } else {
          _countdownTime = _countdownTime - 1;
        }
      });
    }

    _timer = Timer.periodic(oneSec, callback);
  }

  Widget _codeTimeOut() {
    if (_countdownTime < 1) {
      return TextButton(
        child: Text('获取验证码',
            style: TextStyle(color: Theme.of(context).primaryColor)),
        onPressed: () {
          _focusPhone.unfocus();
          _focusCode.unfocus();
          if (!_phoneController.text.isNotEmpty ||
              RegExp(phoneRes).firstMatch(_phoneController.text) == null) {
            showToast("请输入正确手机号码");
          } else {
            //  请求验证码
            _postLoginCode();
          }
        },
      );
    } else {
      return TextButton(
        child: Text('${_countdownTime}s后重新获取',
            style: TextStyle(color: Theme.of(context).colorScheme.onSecondary)),
        onPressed: () {},
      );
    }
  }

  void _postLoginCode() async {
    showLoading(context);
    try {
      ResponseData responseData =
          await Api(context).postLoginCode(_phoneController.text);
      Navigator.pop(context);
      if (responseData.success) {
        if (mounted) {
          setState(() {
            _realName = responseData.data["user"]["realName"];
            _countdownTime = 180;
          });
        }
        //开始倒计时
        startCountdownTimer();
      } else {
        showToast(responseData.msg);
      }
    } catch (e) {
      Navigator.pop(context);
      //登录失败则提示
      Debug.info(e.toString());
      showToast(S.of(context).networkError);
    }
  }

  Widget _inputView(image, controller, obscure, name, fn) {
    return Container(
      width: double.infinity,
      padding: const EdgeInsets.only(left: 10, top: 0, right: 10, bottom: 0),
      decoration: BoxDecoration(
          color: Theme.of(context).colorScheme.background,
          borderRadius: BorderRadius.circular(8.0),
          boxShadow: [
            BoxShadow(
                color: Theme.of(context).colorScheme.onSurface,
                blurRadius: 6.67,
                spreadRadius: 0.33)
          ]),
      child: Row(
        children: [
          Image.asset('images/$image.png', width: 20, height: 20),
          const SizedBox(width: 10),
          Flexible(
              child: TextField(
            controller: controller,
            obscureText: obscure,
            decoration: InputDecoration(
              contentPadding:
                  const EdgeInsets.symmetric(horizontal: 10, vertical: 0),
              hintText: name,
              border: const OutlineInputBorder(borderSide: BorderSide.none),
            ),
            onChanged: (value) {
              fn(value);
            },
          ))
        ],
      ),
    );
  }

  /// 下一步
  void _nextStep() async {
    showLoading(context);
    try {
      ResponseData responseData = await Api(context)
          .postCheckLoginCode(_phoneController.text, _codeController.text);
      Navigator.pop(context);
      if (responseData.success) {
        ///清楚倒计时
        // _timer?.cancel();
        // Navigator.pushNamed(context, "forgetPasswordNext");
        Navigator.push(
            context,
            MaterialPageRoute(
                builder: (context) => ForgetPasswordsNextPage(
                      params: Params(_phoneController.text, _realName),
                    )));
      } else {
        showToast(responseData.msg);
      }
    } catch (e) {
      Navigator.pop(context);
      //登录失败则提示
      showToast(S.of(context).networkError);
    }
  }
}
